using Apps.Common;
using Apps.Models;
using System.Linq;
using System.Collections.Generic;
using LinqToExcel;
using System;
using System.Linq.Expressions;
using Microsoft.Practices.Unity;
using Apps.Locale;
using Apps.BLL.Core;
using System.Transactions;
using System.IO;
using System.Text;
using Apps.Models.LMS;
using Apps.IBLL.LMS;
using Apps.IDAL.LMS;

namespace Apps.BLL.LMS
{
    public partial class LMS_TEMPLATE_DETAILBLL : Virtual_LMS_TEMPLATE_DETAILBLL, ILMS_TEMPLATE_DETAILBLL
    {
        public List<V_LMS_TEMPLATEDETAIL> GetListDetail(string parentId, bool flag=true)//true:显示所有化验指标 
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    if (parentId != "0")
                    {
                        //var queryData= (from  cc in db.LMS_TEMPLATE_DETAIL 
                        //                join s in db.LMS_TEMPLATE on cc.TEMPLATE_ID equals s.TEMPLATE_ID into result1
                        //                from ss in result1.DefaultIfEmpty()
                        //                where cc.TEMPLATE_ID == parentId
                        //                select new
                        //                {
                        //                    TEMPLATE_ID = cc.TEMPLATE_ID,
                        //                    INDEX_ID = cc.INDEX_ID,
                        //                    VALUE_MIN = cc.VALUE_MIN,
                        //                    VALUE_MAX = cc.VALUE_MAX,
                        //                    VALUE_TYPE = cc.VALUE_TYPE,
                        //                    VALUE_SHOW = cc.VALUE_SHOW,
                        //                    VALUE_TEST = cc.VALUE_TEST,
                        //                    VALUE_CHECK = cc.VALUE_CHECK,
                        //                    VALUE_BASE = cc.VALUE_BASE,
                        //                    TEMPLATE_NAME = ss.TEMPLATE_NAME,
                        //                    TEMPLATE_TYPE = ss.TEMPLATE_TYPE,
                        //                    TEMPLATE_DESC = ss.TEMPLATE_DESC,
                        //                    UPDATE_USER = ss.UPDATE_USER,
                        //                    UPDATE_TIME = ss.UPDATE_TIME
                        //                }).ToList();
                        List<V_LMS_TEMPLATEDETAIL> queryData = db.V_LMS_TEMPLATEDETAIL.Where(a => a.TEMPLATE_ID == parentId).ToList();
                        List<PUB_LMS_INDEX> list = db.PUB_LMS_INDEX.Where(a => a.EXTERNAL_ENTRY == 1).ToList();
                        List<V_LMS_TEMPLATEDETAIL> items = new List<V_LMS_TEMPLATEDETAIL>();
                        if (!flag)
                        {
                            for (int i = 0; i < list.Count; i++)
                            {
                                V_LMS_TEMPLATEDETAIL query = new V_LMS_TEMPLATEDETAIL();
                                if (queryData.Count() > 0)
                                {
                                    query = queryData.Where(a => a.INDEX_ID == list[i].INDEX_ID).FirstOrDefault();
                                }
                                V_LMS_TEMPLATEDETAIL item = new V_LMS_TEMPLATEDETAIL
                                {
                                    INDEX_NAME = list[i].INDEX_NAME,
                                    INDEX_DISNAME = list[i].INDEX_DISNAME,
                                    TEMPLATE_ID = query == null ? "" : query.TEMPLATE_ID,
                                    INDEX_ID = list[i].INDEX_ID,
                                    VALUE_MIN = query == null ? 0.00 : query.VALUE_MIN,
                                    VALUE_MAX = query == null ? 0.00 : query.VALUE_MAX,
                                    VALUE_TYPE = query == null ? 0 : query.VALUE_TYPE,
                                    VALUE_SHOW = query == null ? 0 : query.VALUE_SHOW,
                                    VALUE_TEST = query == null ? 0 : query.VALUE_TEST,
                                    VALUE_CHECK = query == null ? 0 : query.VALUE_CHECK,
                                    VALUE_BASE = query == null ? "" : query.VALUE_BASE,
                                    TEMPLATE_NAME = query == null ? "" : query.TEMPLATE_NAME,
                                    TEMPLATE_TYPE = query == null ? 0 : query.TEMPLATE_TYPE,
                                    TEMPLATE_DESC = query == null ? "" : query.TEMPLATE_DESC,
                                    UPDATE_USER = query == null ? "" : query.UPDATE_USER,
                                    UPDATE_TIME = query == null || query.UPDATE_TIME == null ? DateTime.Now : (DateTime)query.UPDATE_TIME
                                };
                                items.Add(item);
                            }
                        }
                        else
                        {
                            if (queryData.Count() == 0)
                            {
                                V_LMS_TEMPLATEDETAIL lmsd = new V_LMS_TEMPLATEDETAIL();
                                LMS_TEMPLATE lms = db.LMS_TEMPLATE.Where(a => a.TEMPLATE_ID == parentId).ToList().FirstOrDefault();
                                lmsd.INDEX_ID = "";
                                lmsd.VALUE_MIN = 0.00;
                                lmsd.VALUE_MAX = 0.00;
                                lmsd.VALUE_TYPE = 0;
                                lmsd.VALUE_SHOW = 0;
                                lmsd.VALUE_TEST = 0;
                                lmsd.VALUE_CHECK = 0;
                                lmsd.VALUE_BASE = "";
                                lmsd.TEMPLATE_ID = lms ==null?"": lms.TEMPLATE_ID;
                                lmsd.TEMPLATE_NAME = lms == null ? "" : lms.TEMPLATE_NAME;
                                lmsd.TEMPLATE_TYPE = lms == null ? 0 : lms.TEMPLATE_TYPE;
                                lmsd.TEMPLATE_DESC = lms == null ? "" : lms.TEMPLATE_DESC;
                                lmsd.UPDATE_TIME = lms == null ? DateTime.Now: (DateTime)lms.UPDATE_TIME;
                                lmsd.UPDATE_USER = lms == null ? "" : lms.UPDATE_USER;
                                queryData.Add(lmsd);
                            }
                            for (int i = 0; i < queryData.Count; i++)
                            {
                                var query = list.Where(a => a.INDEX_ID == queryData[i].INDEX_ID).FirstOrDefault();
                                V_LMS_TEMPLATEDETAIL item = new V_LMS_TEMPLATEDETAIL
                                {
                                    INDEX_NAME = query == null ? "" : query.INDEX_NAME,
                                    INDEX_DISNAME = query == null ? "" : query.INDEX_DISNAME,
                                    TEMPLATE_ID = queryData[i].TEMPLATE_ID,
                                    INDEX_ID = queryData[i].INDEX_ID,
                                    VALUE_MIN = queryData[i].VALUE_MIN,
                                    VALUE_MAX = queryData[i].VALUE_MAX,
                                    VALUE_TYPE = queryData[i].VALUE_TYPE,
                                    VALUE_SHOW = queryData[i].VALUE_SHOW == null ? 0 : queryData[i].VALUE_SHOW,
                                    VALUE_TEST = queryData[i].VALUE_TEST == null ? 0 : queryData[i].VALUE_TEST,
                                    VALUE_CHECK = queryData[i].VALUE_CHECK == null ? 0 : queryData[i].VALUE_CHECK,
                                    VALUE_BASE = queryData[i].VALUE_BASE,
                                    TEMPLATE_NAME = queryData[i].TEMPLATE_NAME,
                                    TEMPLATE_TYPE = queryData[i].TEMPLATE_TYPE,
                                    TEMPLATE_DESC = queryData[i].TEMPLATE_DESC,
                                    UPDATE_USER = queryData[i].UPDATE_USER,
                                    UPDATE_TIME = queryData[i].UPDATE_TIME == null ? DateTime.Now : (DateTime)queryData[i].UPDATE_TIME
                                };
                                items.Add(item);
                            }
                        }
                        return items;

                    }
                    else
                    {
                        var queryData1 = (from r in db.PUB_LMS_INDEX
                                          where r.EXTERNAL_ENTRY == 1
                                          select r).ToList().Select(r => new V_LMS_TEMPLATEDETAIL
                                          {
                                              INDEX_NAME = r.INDEX_NAME,
                                              INDEX_DISNAME = r.INDEX_DISNAME,
                                              TEMPLATE_ID = "",
                                              INDEX_ID = r.INDEX_ID,
                                              VALUE_MIN = 0.00,
                                              VALUE_MAX = 0.00,
                                              VALUE_TYPE = 0,
                                              VALUE_SHOW = 0,
                                              VALUE_TEST = 0,
                                              VALUE_CHECK = 0,
                                              VALUE_BASE = "",
                                              TEMPLATE_NAME = "",
                                              TEMPLATE_TYPE = 0,
                                              TEMPLATE_DESC = "",
                                              UPDATE_USER = "",
                                              UPDATE_TIME = DateTime.Now
                                          });
                        return queryData1.ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
    public class Virtual_LMS_TEMPLATE_DETAILBLL
    {

        [Dependency]
        public ILMS_TEMPLATE_DETAILRepository m_Rep { get; set; }
        public virtual List<LMS_TEMPLATE_DETAILModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<LMS_TEMPLATE_DETAIL> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
                                a => a.TEMPLATE_ID.Contains(queryStr)
                                );
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<LMS_TEMPLATE_DETAILModel> GetPagerList(ref GridPager pager, Expression<Func<LMS_TEMPLATE_DETAIL, bool>> whereLambda)
        {
            IQueryable<LMS_TEMPLATE_DETAIL> queryData = m_Rep.GetList(whereLambda);

            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<LMS_TEMPLATE_DETAILModel> GetList(Expression<Func<LMS_TEMPLATE_DETAIL, bool>> whereLambda)
        {
            IQueryable<LMS_TEMPLATE_DETAIL> queryData = m_Rep.GetList(whereLambda);
            return CreateModelList(ref queryData);
        }

        public virtual List<LMS_TEMPLATE_DETAILModel> GetListByParentId(ref GridPager pager, string queryStr, object parentId)
        {
            return new List<LMS_TEMPLATE_DETAILModel>();
        }

        public virtual List<LMS_TEMPLATE_DETAILModel> CreateModelList(ref IQueryable<LMS_TEMPLATE_DETAIL> queryData)
        {
            List<LMS_TEMPLATE_DETAILModel> modelList = (from r in queryData
                                                        select new LMS_TEMPLATE_DETAILModel
                                                        {
                                                            VALUE_BASE = r.VALUE_BASE,
                                                            VALUE_SHOW = r.VALUE_SHOW,
                                                            VALUE_TYPE = r.VALUE_TYPE,
                                                            VALUE_MAX = r.VALUE_MAX,
                                                            VALUE_MIN = r.VALUE_MIN,
                                                            INDEX_ID = r.INDEX_ID,
                                                            TEMPLATE_ID = r.TEMPLATE_ID,
                                                            VALUE_CHECK=r.VALUE_CHECK,
                                                            VALUE_TEST=r.VALUE_TEST

                                                        }).ToList();
            return modelList;
        }
        public virtual bool Creates(ref ValidationErrors errors, List<LMS_TEMPLATE_DETAIL> model)
        {
            try
            {
                if (m_Rep.Create(model.ToArray()))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Create(ref ValidationErrors errors, LMS_TEMPLATE_DETAILModel model)
        {
            try
            {
                LMS_TEMPLATE_DETAIL entity = m_Rep.GetById(model.TEMPLATE_ID,model.INDEX_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new LMS_TEMPLATE_DETAIL();
                entity.VALUE_CHECK = model.VALUE_CHECK;
                entity.VALUE_TEST = model.VALUE_TEST;
                entity.VALUE_BASE = model.VALUE_BASE;
                entity.VALUE_SHOW = model.VALUE_SHOW;
                entity.VALUE_TYPE = model.VALUE_TYPE;
                entity.VALUE_MAX = model.VALUE_MAX;
                entity.VALUE_MIN = model.VALUE_MIN;
                entity.INDEX_ID = model.INDEX_ID;
                entity.TEMPLATE_ID = model.TEMPLATE_ID;

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Deletes(ref ValidationErrors errors, Expression<Func<LMS_TEMPLATE_DETAIL, bool>> whereLambda)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var entity in db.LMS_TEMPLATE_DETAIL.Where(whereLambda))
                    {
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                    }
                    if (db.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Edit(ref ValidationErrors errors, LMS_TEMPLATE_DETAILModel model)
        {
            try
            {
                LMS_TEMPLATE_DETAIL entity = m_Rep.GetById(model.TEMPLATE_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                entity.VALUE_CHECK = model.VALUE_CHECK;
                entity.VALUE_TEST = model.VALUE_TEST;
                entity.VALUE_BASE = model.VALUE_BASE;
                entity.VALUE_SHOW = model.VALUE_SHOW;
                entity.VALUE_TYPE = model.VALUE_TYPE;
                entity.VALUE_MAX = model.VALUE_MAX;
                entity.VALUE_MIN = model.VALUE_MIN;
                entity.INDEX_ID = model.INDEX_ID;
                entity.TEMPLATE_ID = model.TEMPLATE_ID;
                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual LMS_TEMPLATE_DETAILModel GetById(object id)
        {
            if (IsExists(id))
            {
                LMS_TEMPLATE_DETAIL entity = m_Rep.GetById(id);
                LMS_TEMPLATE_DETAILModel model = new LMS_TEMPLATE_DETAILModel();
                entity.VALUE_CHECK = model.VALUE_CHECK;
                entity.VALUE_TEST = model.VALUE_TEST;
                model.VALUE_BASE = entity.VALUE_BASE;
                model.VALUE_SHOW = entity.VALUE_SHOW;
                model.VALUE_TYPE = entity.VALUE_TYPE;
                model.VALUE_MAX = entity.VALUE_MAX;
                model.VALUE_MIN = entity.VALUE_MIN;
                model.INDEX_ID = entity.INDEX_ID;
                model.TEMPLATE_ID = entity.TEMPLATE_ID;
                return model;
            }
            else
            {
                return null;
            }
        }

        public virtual LMS_TEMPLATE_DETAILModel GetItem(Expression<Func<LMS_TEMPLATE_DETAIL, bool>> whereLambda)
        {

            LMS_TEMPLATE_DETAIL entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            LMS_TEMPLATE_DETAILModel model = new LMS_TEMPLATE_DETAILModel();
            entity.VALUE_CHECK = model.VALUE_CHECK;
            entity.VALUE_TEST = model.VALUE_TEST;
            model.VALUE_BASE = entity.VALUE_BASE;
            model.VALUE_SHOW = entity.VALUE_SHOW;
            model.VALUE_TYPE = entity.VALUE_TYPE;
            model.VALUE_MAX = entity.VALUE_MAX;
            model.VALUE_MIN = entity.VALUE_MIN;
            model.INDEX_ID = entity.INDEX_ID;
            model.TEMPLATE_ID = entity.TEMPLATE_ID;
            return model;
        }

        public virtual bool CheckImportData(string fileName, List<LMS_TEMPLATE_DETAILModel> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<LMS_TEMPLATE_DETAILModel>(x => x.VALUE_BASE, "VALUE_BASE");
            excelFile.AddMapping<LMS_TEMPLATE_DETAILModel>(x => x.VALUE_SHOW, "VALUE_SHOW");
            excelFile.AddMapping<LMS_TEMPLATE_DETAILModel>(x => x.VALUE_TYPE, "VALUE_TYPE");
            excelFile.AddMapping<LMS_TEMPLATE_DETAILModel>(x => x.VALUE_MAX, "VALUE_MAX");
            excelFile.AddMapping<LMS_TEMPLATE_DETAILModel>(x => x.VALUE_MIN, "VALUE_MIN");
            excelFile.AddMapping<LMS_TEMPLATE_DETAILModel>(x => x.INDEX_ID, "INDEX_ID");
            excelFile.AddMapping<LMS_TEMPLATE_DETAILModel>(x => x.TEMPLATE_ID, "TEMPLATE_ID");
            //SheetName
            var excelContent = excelFile.Worksheet<LMS_TEMPLATE_DETAILModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new LMS_TEMPLATE_DETAILModel();
                entity.VALUE_CHECK = row.VALUE_CHECK;
                entity.VALUE_TEST = row.VALUE_TEST;
                entity.VALUE_BASE = row.VALUE_BASE;
                entity.VALUE_SHOW = row.VALUE_SHOW;
                entity.VALUE_TYPE = row.VALUE_TYPE;
                entity.VALUE_MAX = row.VALUE_MAX;
                entity.VALUE_MIN = row.VALUE_MIN;
                entity.INDEX_ID = row.INDEX_ID;
                entity.TEMPLATE_ID = row.TEMPLATE_ID;

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(@"                第 {0} 列发现错误：{1}{2}", rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        public virtual void SaveImportData(IEnumerable<LMS_TEMPLATE_DETAILModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        LMS_TEMPLATE_DETAIL entity = new LMS_TEMPLATE_DETAIL();
                        entity.VALUE_CHECK = model.VALUE_CHECK;
                        entity.VALUE_TEST = model.VALUE_TEST;
                        entity.VALUE_BASE = model.VALUE_BASE;
                        entity.VALUE_SHOW = model.VALUE_SHOW;
                        entity.VALUE_TYPE = model.VALUE_TYPE;
                        entity.VALUE_MAX = model.VALUE_MAX;
                        entity.VALUE_MIN = model.VALUE_MIN;
                        entity.INDEX_ID = model.INDEX_ID;
                        entity.TEMPLATE_ID = model.TEMPLATE_ID;

                        db.LMS_TEMPLATE_DETAIL.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }

        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }

        public void Dispose()
        {

        }

    }
}
